<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <!--<el-form-item label="计划id" prop="planId">
        <el-input
          v-model="queryParams.planId"
          placeholder="请输入计划id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="计划名称" prop="code">
        <el-input v-model="planInfo.name" placeholder="请输入产成品编码" clearable size="small" :disabled="true"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="计划月份" prop="name">
        <el-input v-model="planInfo.month" placeholder="请输入产成品名称" clearable size="small" :disabled="true"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="planInfo.type" placeholder="请选择类型" clearable size="small" :disabled="true">
          <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="planInfo.status" placeholder="状态" clearable size="small" :disabled="true">
          <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <!--<el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>-->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--<el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['produce:planDetail:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['produce:planDetail:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['produce:planDetail:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['produce:planDetail:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planDetailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="计划id" align="center" prop="planId" />-->
      <el-table-column label="产成品编码" align="center" prop="code" />

      <el-table-column label="产成品名称" align="center" prop="name" minWidth="140px">
        <template slot-scope="scope">
          <el-tooltip ceffect="dark" :content="scope.row.name" placement="top-start">
            <span style="color:rgba(213, 241, 255, 0.8) !important">{{ scope.row.name }}</span>
          </el-tooltip>
        
        </template>
      </el-table-column>
      <el-table-column label="所属基地" align="center" prop="deptName" minWidth="100px" />
      <el-table-column label="销售计划数" align="center" prop="salesPlanNum" />
      <el-table-column label="库存" align="center" prop="stockCount" />
      <el-table-column label="单位" align="center" prop="unit" width="50px" />
      <el-table-column label="进度" align="center" prop="progress" />
      <el-table-column label="实际产量-标准箱" align="center" prop="actualNumBox" width="140px" />
      <el-table-column label="生产计划数-标准箱" width="140px" align="center" prop="producePlanNumBox" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="余量分配" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.upFlowFlag == '1'" size="mini" type="text" icon="el-icon-edit"
            @click="handleYLFP(scope.row)" v-hasPermi="['produce:planDetail:ylfp']">余量分配</el-button>
          <label v-if="scope.row.upFlowFlag == '0'">正常</label>
        </template>
      </el-table-column>
      <el-table-column label="分配日计划" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status == '1'" size="mini" type="text" icon="el-icon-edit"
            @click="handleDayPlan(scope.row)" v-hasPermi="['produce:planDetail:fpday']">分配日计划</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" minWidth="120px">
        <template slot-scope="scope">
          <!--<el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleView(scope.row)"
          >查看</el-button>-->
          <!--<el-button
            v-if="scope.row.status == '1'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['produce:plan:edit']"
            >修改</el-button
          >-->
          <el-button v-if="scope.row.progress.replace('%', '') < 100" size="mini" type="text" icon="el-icon-top-right"
            @click="handleDiaobo(scope.row)" v-hasPermi="['produce:plan:remove']">调拨</el-button>
          <!--<el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['produce:planDetail:remove']"
          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改生产计划详情对话框 -->
    <el-dialog v-myFullscreen :title="title" :visible.sync="open" width="900px" append-to-body v-myDialogDrag>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <!--<el-col :span="12">
                <el-form-item label="计划id" prop="planId">
                  <el-input v-model="form.planId" placeholder="请输入计划id" :disabled="openDisabled" />
                </el-form-item>
            </el-col>-->
          <el-col :span="24">
            <el-form-item label="产成品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入产成品名称" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="产成品编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入产成品编码" :disabled="true" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="销售计划数" prop="salesPlanNum">
              <el-input v-model="form.salesPlanNum" placeholder="请输入销售计划数" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="生产计划数" prop="producePlanNum">
              <el-input v-model="form.producePlanNum" placeholder="请输入生产计划数" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="任务状态">
              <!--<el-radio-group v-model="form.status" >
                    <el-radio
                      v-for="dict in statusOptions"
                      :key="dict.dictValue"
                      :label="dict.dictValue"
                    >{{dict.dictLabel}}</el-radio>
                  </el-radio-group>-->
              <el-select v-model="form.status" placeholder="请选择状态" clearable size="small">
                <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" placeholder="请输入备注" :disabled="openDisabled" />
                </el-form-item>
            </el-col>-->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!openDisabled">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--分配日计划弹窗-->
    <el-dialog v-myFullscreen :title="title" :visible.sync="open2" width="500px" append-to-body v-myDialogDrag>
      <el-form ref="form" :model="form" :rules="rules2" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="生产日期区间" prop="planDate">
              <el-date-picker :editable="false" v-model="planDate" value-format="yyyy-MM-dd" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="生产班组" prop="groups">
              <!--<el-input v-model="form.groups" placeholder="请选择生产班组"  />-->
              <el-select v-model="form.groups" placeholder="请选择所属班组" clearable>
                <el-option v-for="dict in groupsListOptions" :key="dict.id" :label="dict.name"
                  :value="dict.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="填写生产总量" prop="currentCount">
              <el-input v-model="form.currentCount" placeholder="请输入销售计划数" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="" prop="producePlanNum" style="margin-top: -20px">
              <!--<el-input v-model="form.producePlanNum" placeholder="请输入销售计划数"  :disabled = "true" />-->
              <div style="text-align: left">
                计划总量：{{ form.producePlanNum }}, 已分配总量：{{
                form.fpCount
                }}
              </div>
            </el-form-item>
          </el-col>

          <!--<el-col :span="24">-->
          <!--<el-form-item label="可分配總量" prop="availableCount">-->
          <!--<el-input v-model="form.availableCount" placeholder="可分配总量"  :disabled = "true" />-->
          <!--</el-form-item>-->
          <!--</el-col>-->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!openDisabled">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>

    <!--余量分配弹窗-->
    <el-dialog v-myFullscreen :title="title" :visible.sync="open3" width="500px" append-to-body v-myDialogDrag>
      <el-form ref="form" :model="form2" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="" prop="producePlanNum" style="margin-top: -20px">
              <!--<el-input v-model="form.producePlanNum" placeholder="请输入销售计划数"  :disabled = "true" />-->
              <div style="text-align: left; font-size: 25px">
                全部余量：{{ form2.totalCount }}
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!openDisabled">
        <el-button type="primary" @click="submitForm3">确 定</el-button>
        <el-button @click="cancel3">取 消</el-button>
      </div>
    </el-dialog>

    <!--品项弹窗-->
    <el-dialog v-myFullscreen :title="title" :visible.sync="open4" width="500px" append-to-body v-myDialogDrag>
      <el-form ref="form" :model="form4" :rules="rules4" label-width="120px">
        <el-row>
          <el-col :span="24"> </el-col>
          <el-col :span="24">
            <el-form-item label="品项名称" prop="name">
              <el-input v-model="form4.name" placeholder="" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="目标基地" prop="toDeptId">
              <!-- <el-input
                 v-model="form2.name"
                 placeholder="请选择目标基地"
                 style="width: 200px"
               />-->
              <el-select v-model="form4.toDeptId" placeholder="请选择目标基地">
                <el-option v-for="dict in factoryListOptions" :key="dict.deptId" :label="dict.name" :value="dict.deptId"
                  :disabled="dict.deptId == form4.deptId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调拨总量" prop="count">
              <el-input v-model="form4.count" placeholder="请输入调拨数量" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="" prop="producePlanNum" style="margin-top: -20px">
              <!--<el-input v-model="form.producePlanNum" placeholder="请输入销售计划数"  :disabled = "true" />-->
              <div style="text-align: left">
                可调拨总量：{{ form4.leftCount }}
              </div>
            </el-form-item>
          </el-col>

          <!--<el-col :span="24">-->
          <!--<el-form-item label="可分配總量" prop="availableCount">-->
          <!--<el-input v-model="form.availableCount" placeholder="可分配总量"  :disabled = "true" />-->
          <!--</el-form-item>-->
          <!--</el-col>-->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!openDisabled">
        <el-button type="primary" @click="submitForm4">确 定</el-button>
        <el-button @click="cancel4">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listPlanDetail,
    getPlanDetail,
    getPlanCountDetail,
    delPlanDetail,
    addPlanDetail,
    updatePlanDetail,
    getTeamGroupSelect,
    fpPlanDay,
    YLFP,
    PXTB,
    getFactoryList,
  } from "@/api/produce/planDetail/planDetail";

  export default {
    name: "PlanDetail",
    data() {
      return {
        //弹窗是否禁止编辑
        openDisabled: true,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 生产计划详情表格数据
        planDetailList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        open2: false,
        open3: false,
        open4: false,
        // 单项任务完成状态 0：已停止， 1：进行中， 2：已完成字典
        statusOptions: [],
        typeOptions: [],
        groupsListOptions: [],
        factoryListOptions: [],
        planDate: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 50,
          planId: this.$route.query.planId,
          code: null,
          name: null,
          status: null,
        },
        planInfo: {
          name: this.$route.query.name,
          month: this.$route.query.month,
          status: this.$route.query.status,
          type: this.$route.query.type,
        },
        // 表单参数
        form: {},
        form2: {
          totalCount: null,
          id: null,
        },

        form4: {
          leftCount: null,
          count: null,
          code: null,
          name: null,
          id: null,
          toDeptId: null,
          deptId: null,
        },
        // 表单校验
        rules: {
          salesPlanNum: { validator: this.$rules.number("销售计划数") },
          producePlanNum: { validator: this.$rules.number("生产计划数") },
        },
        rules2: {
          groups: { validator: this.$rules.required("班组名称") },
          currentCount: { validator: this.$rules.number("计划分配数") },
        },
        rules4: {
          toDeptId: { validator: this.$rules.required("目标基地") },
          count: { validator: this.$rules.number("调拨数目") },
        },
      };
    },
    created() {
      this.getList();
      this.getDicts("plan_status").then((response) => {
        this.statusOptions = response.data;
      });
      this.getDicts("plan_type").then((response) => {
        this.typeOptions = response.data;
      });
      this.getTeamGroupSelect();
      this.getFactoryList();
    },
    methods: {
      /** 查询生产计划详情列表 */
      getList() {
        this.loading = true;
        listPlanDetail(this.queryParams).then((response) => {
          this.planDetailList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },

      getFactoryList() {
        getFactoryList().then((response) => {
          this.factoryListOptions = response.data;
        });
      },

      handleDiaobo(row) {
        this.title = "品项调拨";
        this.open4 = true;
        this.openDisabled = false;
        this.form4.id = row.id;
        this.form4.leftCount = row.producePlanNum - row.actualNum;
        this.form4.code = row.code;
        this.form4.name = row.name;
        this.form4.deptId = row.deptId;
      },
      getTeamGroupSelect() {
        return getTeamGroupSelect().then((response) => {
          this.groupsListOptions = response.rows;
        });
      },
      // 单项任务完成状态 0：已停止， 1：进行中， 2：已完成字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      cancel2() {
        this.open2 = false;
        this.reset();
      },
      cancel3() {
        this.open3 = false;
      },
      cancel4() {
        this.open4 = false;
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          planId: null,
          planDetailId: null,
          code: null,
          name: null,
          unit: null,
          progress: null,
          salesPlanNum: null,
          producePlanNum: null,
          actualNum: null,
          currentCount: null,
          planDateStart: null,
          planDateEnd: null,
          availableCount: null,
          fpCount: null,
          status: "0",
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          delFlag: null,
          remark: null,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.openDisabled = false;
        this.open = true;
        this.title = "添加生产计划详情";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.openDisabled = false;
        const id = row.id || this.ids;
        getPlanDetail(id).then((response) => {
          this.form = response.data;
          this.open = true;
          this.title = "修改生产计划详情";
        });
      },
      handleDayPlan(row) {
        getPlanCountDetail(row.id).then((response) => {
          this.form = response.data;
          this.title = "分配日计划";
          this.open2 = true;
          this.openDisabled = false;
        });
      },
      handleYLFP(row) {
        this.title = "余量分配";
        this.open3 = true;
        this.openDisabled = false;
        this.form2.totalCount = row.actualNum - row.producePlanNum;
        this.form2.id = row.id;
        console.log(this.form2.totalCount);
      },
      /** 查看按钮 */
      handleView(row) {
        this.reset();
        this.openDisabled = true;
        const id = row.id || this.ids;
        getPlanDetail(id).then((response) => {
          this.form = response.data;
          this.open = true;
          this.title = "查看生产计划详情";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.id != null) {
              updatePlanDetail(this.form).then((response) => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              const rLoading = this.openLoading();
              addPlanDetail(this.form)
                .then((response) => {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  rLoading.close();
                  this.getList();
                })
                .catch((error) => {
                  rLoading.close();
                });
            }
          }
        });
      },

      submitForm2() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.currentCount <= this.form.availableCount) {
              // console.log(this.planDate.length);
              if (this.planDate.length > 0) {
                this.form.planDateStart = this.planDate[0];
                this.form.planDateEnd = this.planDate[1];
              } else {
                this.$message.error("分配区间不能为空");
                return;
              }
              fpPlanDay(this.form).then((response) => {
                this.msgSuccess("分配日计划成功");
                this.open2 = false;
                this.openDisabled = true;
              });
            } else {
              this.$message.error("可分配总量不足");
              return;
            }
            /*
            if (this.form.id != null) {
              updatePlanDetail(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              const rLoading = this.openLoading();
              addPlanDetail(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                rLoading.close();
                this.getList();
              }).catch((error) => {
                rLoading.close();
              });;
            }*/
          }
        });
      },

      submitForm4() {
        // console.log("tb");
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form4.count <= this.form4.leftCount) {
              /* fpPlanDay(this.form).then((response) => {
                this.msgSuccess("分配日计划成功");
                this.open2 = false;
                this.openDisabled = true;
              });*/
              PXTB(this.form4).then((response) => {
                this.msgSuccess(response.msg);
                this.open4 = false;
                this.openDisabled = true;
                this.getList();
              });
            } else {
              this.$message.error("可调拨总量不足");
              return;
            }
            /*
            if (this.form.id != null) {
              updatePlanDetail(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              const rLoading = this.openLoading();
              addPlanDetail(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                rLoading.close();
                this.getList();
              }).catch((error) => {
                rLoading.close();
              });;
            }*/
          }
        });
      },

      submitForm3() {
        YLFP(this.form2).then((response) => {
          this.msgSuccess(response.msg);
          this.open3 = false;
          this.openDisabled = true;
          this.getList();
        });
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm(
          '是否确认删除生产计划详情编号为"' + ids + '"的数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return delPlanDetail(ids);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(() => { });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download(
          "produce/planDetail/export",
          {
            ...this.queryParams,
          },
          "生产计划详情" + this.parseTime(new Date()) + ".xlsx"
        );
      },
    },
  };
</script>